<template>
  <div>
    <Menu mode="horizontal" @on-select='lowerStep' :active-name="modaleshow">
      <MenuItem name="1">基础标准管理</MenuItem>
      <MenuItem name="2">现场标准管理</MenuItem>
      <MenuItem name="3">班组标准管理</MenuItem>
    </Menu>
    <Form :label-width="100" style="margin-top: 10px" ref="form1" :model="form1">
      <div v-if="switchFlag">
        <Row :gutter="16" class="query-form">
          <i-col span="8">
            <FormItem label="问题描述：">
              <Input type="text" v-model="form1.rpoblemDesc"/>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="指派人员：">
              <Select class="query-form-el" v-model="form1.assignorId">
                <Option v-for="item in assignorList" :value="item.userId" :key="item.userId">{{ item.userName }}
                </Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="整改状态：">
              <Select v-model="form1.verification">
                <Option value="1">已完成</Option>
                <Option value="0">整改中</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="16" class="query-form2">

          <i-col span="8" offset="16">
            <div style="float: right;">
              <Button class="ivu-btn-query" icon="md-search" @click="querySlect">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
              <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text">收起
                <Icon type="ios-arrow-up"/>
              </Button>
            </div>
          </i-col>
        </Row>
      </div>
      <div v-else>
        <Row :gutter="16" class="query-form2">
          <i-col span="8">
            <FormItem label="问题描述：">
              <Input type="text" v-model="form1.rpoblemDesc"/>
            </FormItem>
          </i-col>
          <i-col span="8">
            <FormItem label="指派人员：">
              <Select class="query-form-el" v-model="form1.assignorId">
                <Option v-for="item in assignorList" :value="item.userId" :key="item.userId">{{ item.userName }}
                </Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="8">
            <div style="float: right;">
              <Button class="ivu-btn-query" icon="md-search" @click="querySlect">查询</Button>
              <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
              <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">展开
                <Icon type="ios-arrow-down"/>
              </Button>
            </div>
          </i-col>
        </Row>
      </div>

      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-cloud-download" @click="downloadFile">导出</Button>
          <Button size="large" class="ivu-btn-add" icon="md-home" @click="back">返回</Button>
          <!--          <Button size="large" class="ivu-btn-add" icon="md-checkbox-outline" v-if="this.reportSelectAll.length !== 0" @click="submitReportSelect">确认问题</Button>-->
          <!--          <Button size="large" class="ivu-btn-add" icon="md-people" @click="openUser"
                            v-if="(shuji || jingli||minister || positions.includes(postionName))&&!this.$route.query.procinstState">
                      问题指派
                    </Button>-->
          <!--          <Button size="large" class="ivu-btn-add" icon="md-people" @click="openUser" v-if="this.$route.query.type == '2'">问题指派</Button>-->
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" class="table" no-data-text="没有查询到相关数据！" :loading="buttonLoading"
           size="small"
           highlight-row stripe border :columns="columns1" width="100%" :data="dataTable"
           @on-selection-change="reportSelect">
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal title="审计问题详情" :transfer=false v-model="model3" class="modal-view-detail" :width=900 :styles="{top: '10px'}">
      <Form ref="viewForm" :label-width="100">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="审计任务：">
              {{ showdata.planTaskName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="审计单位：">
              {{ showdata.auditedOrgName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="审计时间：" prop="auditTime">
              {{ this.formatDate(new Date(showdata.auditTime), 'yyyy-MM-dd') }}
            </FormItem>
          </Col>
          <Col span="11">

          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="项目：">
              {{ showdata.factorName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="审计标准：">
              {{ showdata.executorName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="审计内容：">
              {{ showdata.subitemName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="扣分：" prop="auditScore">
              {{ showdata.auditScore }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="项目分值：">
              {{ showdata.factorScore }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">

          <Col span="23">
            <FormItem label="问题状态:">
              {{ showdata.problemStateName }}
            </FormItem>
          </Col>

        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="问题描述：" prop="rpoblemDesc">
              {{ showdata.rpoblemDesc }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="问题图片:">
              <div class="demo-upload-list" style="display:inline;margin:2px" v-for="item in upLoadList1"
                   :key="item.id">
                <img style="width:50px;height:50px;" @click="handleView(item.name,item.url)" :src="item.url">
              </div>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">

          <Col span="11">
            <FormItem label="整改人：">
              {{ showdata.personName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="整改人电话：">
              {{ showdata.phone }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="整改状态：">
              {{ showdata.verification === '0' ? '整改中' : showdata.verification === '1' ? '已完成' : '' }}
            </FormItem>
          </Col>

          <Col span="11">
            <FormItem label='问题类别：' prop='problemCategory'>
              {{ showdata.problemCategoryName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="完成时限：">
              {{ renderViewDate(showdata.completeTime) }}
            </FormItem>
          </Col>
          <Col span="11">

          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="整改方案：" prop="rectifyPlan">
              {{ showdata.rectifyPlan }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='当前进展描述：'>
              {{ showdata.completion }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="备注：">
              {{ showdata.note }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="整改后图片:">
              <div class="demo-upload-list" style="display:inline;margin:2px" v-for="item in uploadItems"
                   :key="item.id">
                <img style="width:50px;height:50px;" @click="handleView(item.name,item.url)" :src="item.url">
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
      </div>
    </Modal>
    <Modal title="审计问题整改" :transfer=false v-model="model12" class="modal-view-detail" :width=900
           :styles="{top: '10px'}">
      <Form :model="showdata" ref="showdata" :label-width="100" :rules="ruleCustom">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="审计任务：">
              {{ showdata.planTaskName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="审计单位：">
              {{ showdata.auditedOrgName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="审计时间：" prop="auditTime">
              {{ this.formatDate(new Date(showdata.auditTime), 'yyyy-MM-dd') }}
            </FormItem>
          </Col>
          <Col span="11">

          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="项目：">
              {{ showdata.factorName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="审计标准：">
              {{ showdata.executorName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="审计内容：">
              {{ showdata.subitemName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="扣分：" prop="auditScore">
              {{ showdata.auditScore }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="项目分值：">
              {{ showdata.factorScore }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">

          <Col span="23">
            <FormItem label="问题状态:">
              {{ showdata.problemStateName }}
            </FormItem>
          </Col>

        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="问题描述：" prop="rpoblemDesc">
              {{ showdata.rpoblemDesc }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="问题图片:">
              <div class="demo-upload-list" style="display:inline;margin:2px" v-for="item in upLoadList1"
                   :key="item.id">
                <img style="width:50px;height:50px;" @click="handleView(item.name,item.url)" :src="item.url">
              </div>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">

          <Col span="11">
            <FormItem label="整改人：" prop="personName">
              <Input type="text" v-model="showdata.personName"/>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="整改人电话：" prop="phone">
              <Input type="text" v-model="showdata.phone"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label="整改状态：" prop="verification">
              <Select v-model="showdata.verification">
                <Option value="0">整改中</Option>
                <Option value="1">已完成</Option>
              </Select>
            </FormItem>
          </Col>

          <Col span="11">
            <FormItem label='问题类别：' prop='problemCategory'>
              <Select v-model="showdata.problemCategory">
                <OptionGroup label="基础管理">
                  <Option v-for="item in sceneList" :value="item.codingCodeId" :key="item.codingCodeId">
                    {{ item.codingName }}
                  </Option>
                </OptionGroup>
                <OptionGroup label="现场管理">
                  <Option v-for="item in basicList" :value="item.codingCodeId"
                          :key="item.codingCodeId">{{ item.codingName }}
                  </Option>
                </OptionGroup>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="11">
            <FormItem label='完成时限：' prop='completeTime'>
              <DatePicker type="date" placeholder="请选择日期" style="width: 100%"
                          v-model='showdata.completeTime' :disabled="completeTime"
                          :editable="editable"></DatePicker>
            </FormItem>
          </Col>
          <Col span="11">

          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="整改方案：" prop="rectifyPlan">
              <Input v-model="showdata.rectifyPlan" type="textarea" :maxlength="1024" show-word-limit :rows="3"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label='当前进展描述：'>
              <Input type='textarea' v-model='showdata.completion' :maxlength="1024" show-word-limit :rows="3"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="备注：">
              <Input v-model="showdata.note" type="textarea" :rows="3"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="23">
            <FormItem label="整改后图片:">
              <div>
                <Upload ref="upload"
                        :before-upload="beforeUpload"
                        :show-upload-list="true"
                        :max-size="10240"
                        :format="['jpg','jpeg','png','gif']"
                        accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                        multiple
                        type="drag"
                        :action="fileUrl">
                  <div style="padding: 10px">
                    <Icon type="ios-cloud-upload" size="40" style="color: #3399ff"></Icon>
                    <p>点击将文件拖拽到这里上传</p>
                  </div>
                </Upload>
              </div>
              <div v-if="uploadItems.length > 0">
                <div v-for="item in uploadItems" :key='item.id'>
                  <a @click="downloadFiles(showdata.id,item)"><span
                      style="color: #3399ff;margin-left: 5px"> {{ item.fileName }}</span>
                  </a>
                  <a @click="remove1(showdata.id, item.id)"><span
                      style="color: #3399ff;margin-left: 5px">删除</span>
                  </a>
                </div>
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button class='ivu-btn-save' :loading="submitLoading" @click="submit('showdata')">确定</Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal title="图片查看" v-model="visible">
      <img :src="viewUrl" v-if="visible" style="width: 100%">
      <div slot="footer">
        <Button @click="visible=false" class='ivu-btn-save'>关闭</Button>
      </div>
    </Modal>

    <Modal title="指派整改" :transfer=false footer-hide v-model="model4" :width=900>
      <userManager :model="true" @getSelectModelData="getSelectModelData"
                   :company-name="user.companyName"></userManager>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
      </div>
    </Modal>

  </div>

</template>

<script>
import {Api} from '@/api/index.js'

import {sessionStorage} from '@/common/cacheUtils.js'

import {formatDate} from '@/tools/index'
import userManager from "./userManager.vue"

export default {
  components: {
    userManager
  },
  data() {

    const expectUserVal = (rule, value, callback) => {
      if (this.dataForm.expectUser !== null && this.dataForm.expectUser !== undefined) {
        callback();
      } else {
        callback(new Error(' '));
      }
    };
    const assignUserIdVal = (rule, value, callback) => {
      if (this.dataForm.assignUserId !== null && this.dataForm.assignUserId !== undefined) {
        callback();
      } else {
        callback(new Error(' '));
      }
    };

    return {
      audio: "",
      amr: null,
      misson: [],
      modaleshow: "1",
      auditHandlers: [],
      model2: false,
      basicList: [],
      executorId: '',
      sceneList: [],
      provideOrdId: '',
      switchFlag: false,
      model12: false,
      missonList: [],
      showdata: {},
      auditList: [],
      expertSelectModal: false,
      tempSelectModal: false,
      fileUrl: Api.interestedPartiesUserFile,
      upLoadList1: [],
      form1datacopy: {},
      missionSelectModal: false,
      form1: {},
      dataForm: {},
      chkProblem: {},
      completeTime: null,
      upLoadList2: [],
      //分页参数
      submitLoading: false,
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      assignorList: [],
      user: sessionStorage('userId').getObject('userId'),
      contentList: [],
      columns1: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left',
        },
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: "整改人",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.row.personName || '--');
          }
        },
        {
          title: "整改状态",
          width: 150,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            let color = 'green';
            if (params.row.verification == undefined || params.row.verification == null || params.row.verification === '0') {
              color = 'red';
            }
            return h('div', [
              h('span', {
                style: {
                  color: color
                }
              }, params.row.verification === '1' ? '已完成' : '整改中')
            ]);
          }
        },
        {
          minWidth: 300,
          title: '问题描述',
          key: 'rpoblemDesc',
          align: 'center',
          tooltip: true
        },
        {
          minWidth: 180,
          title: '审计标准',
          key: 'executorName',
          align: 'center',
          tooltip: true
        },
        {
          minWidth: 180,
          title: '项目',
          key: 'factorName',
          align: 'center',
        },
        {
          minWidth: 250,
          title: '审计内容',
          key: 'subitemName',
          align: 'center',
        },

        {
          minWidth: 250,
          title: '问题图片',
          align: 'center',
          key: 'imgsrc',
          render: (h, params) => {
            if (!params.row.pictureId) {
              return h('span', '--');
            }
            let ps = params.row.pictureId.split(':')
            let hFn = []
            ps.forEach(v => {
              if (v) {
                let url = this.fileUrl + '/file/' + v
                hFn.push(
                    h('img', {
                      style: {
                        width: "30px",
                        margin: "3px",
                        cursor: "pointer"
                      },
                      attrs: {
                        src: url
                      },
                      on: {
                        click: () => {
                          this.handleView('', url)
                        }
                      }
                    })
                )
              }
            })
            return h('div', [...hFn
            ]);
          }
        },
        {
          minWidth: 250,
          title: '整改后图片',
          align: 'center',
          key: 'fileId',
          render: (h, params) => {
            if (!params.row.fileId) {
              return h('span', '--');

            }
            let ps = params.row.fileId.split(':')
            let files = []
            ps.forEach(v => {
              if (v) {
                let url = this.fileUrl + '/file/' + v
                files.push(
                    h('img', {
                      style: {
                        width: "30px",
                        margin: "3px",
                        cursor: "pointer"
                      },
                      attrs: {
                        src: url
                      },
                      on: {
                        click: () => {
                          this.handleView('', url)
                        }
                      }
                    })
                )
              }
            })
            return h('div', [...files
            ]);
          }
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 150,
          align: 'center',
          render: (h, params) => {
            let problemState = params.row.problemState
            if (this.$route.query.procinstState == undefined || this.$route.query.procinstState == null || this.$route.query.procinstState == '5') {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                  },
                  on: {
                    click: () => {
                      this.showData(params, 2);
                    }
                  }
                }, '整改'),
              ]);

            } else {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
              ]);
            }

          }
        }
      ],
      ruleCustom: {
        personName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        problemCategory: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        completeTime: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        rectifyPlan: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],

        phone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(value))) {
              callback(' ');
              // this.$Message.error("请填写有效的的手机号")
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],

        verification: [{
          validator: (rule, value, callback) => {
            if (this.showdata.verification == null || this.showdata.verification == '' || this.showdata.verification == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],

      },
      ruleCustomModel: {
        rectLeaderId: [
          {required: true, message: '  ', trigger: 'blur'}
        ],
        rectTime: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        rectDesc: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        auditedOrgId: [
          {required: true, message: '  ', trigger: 'change'}
        ],

        stdRankId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        groupLeaderName: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        cover: [
          {required: true, message: '  ', trigger: 'change'}
        ],


        planEnd: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        planStart: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],

      },
      model4: false,
      dataTable: [],
      model1: false,
      model11: false,
      buttonLoading: false, tableHeight: '',
      model3: false,
      viewForm: {},
      positions: ['安全总监', '站长'],
      setCurrentExpectUserName: {},
      setCurrentAssignUserName: {},
      reportSelectAll: [],
      uploadList: [],
      uploadImgs: [],
      visible: false,
      viewUrl: Api.downloadPTWSchemeFile,
      upUrl: Api.uploadPTWFiles,
      minister: false,
      jingli: false,
      shuji: false,
      editable: false,
      postionName: '',
      uploadItems: [],
    }
  },
  mounted: function () {
    this.postionName = this.user.position.positionName
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    if (this.postionName) {
      this.minister = this.postionName.search("部长") != -1
      this.jingli = this.postionName.search("经理") != -1
      this.shuji = this.postionName.search("书记") != -1
    }
    if (this.$route.query.businessId) {
      this.form1.businessId = this.$route.query.businessId;
    }
    this.$http.get(Api.queryCodeDetailBySuperiorcode + '/NOT-00007000000001', {params: {}}).then((res) => {
      this.basicList = res.data.data;
    });
    this.$http.get(Api.queryCodeDetailBySuperiorcode + '/NOT-00007000000004', {params: {}}).then((res) => {
      this.sceneList = res.data.data;
    });
    this.selectassignor();
    this.load()
  },

  methods: {
    lowerStep(name) {
      this.modaleshow = name
      this.load();
    },
    load() {
      if (this.modaleshow == '1') {
        this.executorId = this.$route.query.basicsId
        // this.executorName = this.$route.query.basicsName
      } else if (this.modaleshow == '2') {
        this.executorId = this.$route.query.sceneId
        // this.executorName = this.$route.query.sceneName
      } else {
        this.executorId = this.$route.query.teamId
        // this.executorName = this.$route.query.teamName
      }
      this.querySlect();
    },
    selectassignor() {
      let _this = this;
      let url = Api.getAssignor;
      this.$http.get(url + "/" + this.$route.query.missionId).then((res) => {
        this.assignorList = res.data.data;
        /*
                if ((_this.jingli||_this.minister || _this.positions.includes(_this.postionName))&&!_this.$route.query.procinstState){
                  _this.assignorList.splice(0,1);
                }else{
                  _this.$set(_this.form1,'assignorId',_this.assignorList[0].userId)
                }*/
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    play(url, amr) {
      let _this = this;
      amr.onEnded(function () {
        _this.audio = "md-play"
      });
      if (amr.isInit()) {
        if (amr.isPlaying()) {
          amr.pause();
          this.audio = "md-play"
        } else {
          amr.play();

          this.audio = "md-square"
        }

      } else {

        amr.initWithUrl(url).then(function () {
          amr.play();
          _this.audio = "md-square"
        })
      }

    },
    back() {
		this.$router.back();
      // this.$router.push('/problemRectList')
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 44;
      } else {
        this.tableHeight = this.tableHeight + 44;
      }
    },
    downloadFiles(perfId, file) {
      let url = Api.interestedPartiesUserFile + '/file/' + file.id;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        console.log(res)
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    openUser() {
      if (this.reportSelectAll.length > 0) {
        this.model4 = true
      } else {
        this.$Message.warning("请先勾选审计问题")
      }

    },
    renderViewDate(date) {
      if (!date) return "";
      return formatDate(new Date(date), "yyyy-MM-dd");
    },
    remoteMethod1(query) {
      this.misson = []
      for (var i = 0; i < this.missonList.length; i++) {
        if (this.missonList[i].missionName.indexOf(query + "") >= 0) {
          this.misson.push(this.missonList[i]);
        }
      }
    },
    submitMess(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
          this.form1datacopy.createUsrId = userId;
          this.form1datacopy.createOrgId = orgId;

          this.$Modal.confirm({
            title: '指派整改确认',
            content: '<p>此操作无法撤销，请确认指派整改信息正确。</p>',
            okText: '确认',
            onOk: () => {
              this.form1datacopy.planTaskId = this.form1datacopy.missionId;
              this.$http.post(Api.createAdtProblemRect, this.form1datacopy).then((res) => {
                if (res.status === 200) {
                  this.$Message.success('指派成功');
                  this.model2 = false;
                  this.query()
                } else if (res.data.status === 201) {
                  this.$Message.error(res.data.msg);
                  this.model2 = false;
                }
              }).catch(e => {
                this.model2 = false;
                this.query();
                this.$Message.error("数据获取失败")
              })
            },
            cancelText: '取消'
          });
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    getSelectModelData(row) {
      let _this = this;
      let config = {
        title: '系统提示',
        content: '确认指派给该用户吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: function () {
          let data = {
            userId: row.userId,
            missionId: _this.$route.query.missionId,
            problemIds: _this.reportSelectAll,
            createUserId: sessionStorage('userId').getObject('userId').userId,
            createOrgId: sessionStorage('userId').getObject('userId').orgInfo.orgId,
          }
          _this.$http.post(Api.auditAssignRectification, data).then((res) => {
            if (res.data.status === 200) {
              _this.reportSelectAll = [];
              _this.$Message.success('指派成功');
              _this.model4 = false;
              _this.selectassignor();
              _this.query();
            } else if (res.data.status === 201) {
              _this.$Message.error(res.data.msg);
              _this.model4 = false;
            }
          }).catch(e => {
            _this.model4 = false;
            _this.query();
            _this.$Message.error("数据获取失败")
          })

        },
      }
      this.$Modal.confirm(config);

    },
    downloadFileAll() {
      let data = this.$route.query;
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      this.$http.get(Api.downloadAdtProblemMgr, {
        params: data,
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "审计问题清单(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    openExpertSelector(isLeader) {
      this.$refs.selExpert.isLeader = isLeader
      this.expertSelectModal = true;

    },
    missonListChange(val) {
      this.form1.planTaskId = val
      this.query();
    },
    selectCodingSort() {
      let id = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserId"]
      this.$http.get(Api.getAllTasksByUseId, {params: {id}}).then((res) => {
        this.missonList = res.data.data;
        if (this.missonList.length != 0) {
          this.form1.planTaskId = this.missonList[0].missionId;
          this.misson = this.missonList;
        }
        this.query();
      });

    },
    onCancel() {
      this.model3 = false
    },
    problemStateSelect(appStatus) {
      this.form1datacopy.problemState = appStatus && appStatus.value;
      this.form1datacopy.problemStateName = appStatus && appStatus.label;
    },
    getActivityExpertData(row) {
      this.form1.expertName = row.userName
      this.form1.expertId = row.userId
      this.expertSelectModal = false;
    },
    async getActivityData(row) {
      this.form1datacopy.factorId = row.id
      this.form1datacopy.executorId = row.executorId
      this.form1datacopy.factorScore = row.score
      this.form1datacopy.auditScore = 1
      if (row.type == '1') {
        this.form1datacopy.executorName = this.$route.query.basicsName;
      } else if (row.type == '2') {
        this.form1datacopy.executorName = this.$route.query.sceneName;
      } else if (row.type == '3') {
        this.form1datacopy.executorName = this.$route.query.teamName;
      }


      this.form1datacopy.factorName = row.projectName
      await this.selectByContent();
      this.tempSelectModal = false;
    },
    checkSubitemId(item) {
      this.form1datacopy.subitemId = item.value;
      this.form1datacopy.subitemName = item.label;

    },
    async selectByContent() {
      await this.$http.get(Api.queryContentParentId + this.form1datacopy.factorId, {params: {}}).then((res) => {
        this.contentList = res.data.data;
      });
    },
    openTempSelector() {
      if (this.form1datacopy.sceneId && this.form1datacopy.basicsId && this.form1datacopy.teamId) {
        this.tempSelectModal = true;
        this.$refs.selTemplate.init(this.form1datacopy.sceneId, this.form1datacopy.basicsId, this.form1datacopy.teamId);
      } else {
        this.$Message.warning("请选择审计任务！");
      }

    },
    closeExpertModal() {
      this.expertSelectModal = false;
    },
    closeTemptSelectModal() {
      this.tempSelectModal = false;
    },
    setUserName1(data) {
      this.form1datacopy.auditorName = data;
    },
    setUserId1(data) {
      this.form1datacopy.auditorId = data[data.length - 1];
    },
    reportSelect(select) {
      this.reportSelectAll = [];
      select.forEach(item => {
        this.reportSelectAll.push(item.problemId)
      });
    },
    querySlect() {
      this.pagedata.currentPage = 1
      this.query();
    },
    submitReportSelect() {
      let _this = this;
      let config = {
        title: '系统提示',
        content: '确认问题后不能修改是否确认?',
        okText: '确定',
        cancelText: '取消',
        onOk: function () {
          this.$http.post(Api.submitSelectAdtProblem, _this.reportSelectAll).then((res) => {
            if (res.data.status == '200') {
              _this.$Message.success("确认成功");
              _this.reportSelectAll = [];
              _this.query();
            } else {
              _this.$Message.success(res.data.msg);
              _this.query();
            }

          }).catch(e => {
            this.query();
            this.$Message.error("失败")
          })

        }

      }


      this.$Modal.confirm(config);

    },
    selectMission(row) {
      //this.$refs.childUser.resetCurrentOrg();
      this.missionSelectModal = false
      this.form1datacopy.planTaskName = row.missionName
      this.form1datacopy.planTaskId = row.missionId

      this.form1datacopy.auditedOrgName = row.auditedOrgName
      this.form1datacopy.auditedOrgId = row.auditedOrgId
      this.form1datacopy.problemState = '0'
      this.form1datacopy.problemStateName = '待确认'
      this.form1datacopy.auditorName = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserName"]
      this.form1datacopy.auditorId = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserId"]
      this.form1datacopy.sceneId = row.sceneId
      this.form1datacopy.teamId = row.teamId
      this.form1datacopy.basicsId = row.basicsId
      this.provideOrdId = row.auditedOrgId
      this.$refs.selTemplate.init(this.form1datacopy.sceneId, this.form1datacopy.basicsId, this.form1datacopy.teamId);


    },

    verifySuffix(fileName) {
      const suffix = `(jpg|jpeg|png|gif|bmp)`
      var regular = new RegExp(`.*\.${suffix}`)
      return regular.test(fileName)
    },
    beforeUpload(file) {

      if (!this.verifySuffix(file.name)) {
        this.$Message.error("只允许上传图片")
      } else {
        let formData = new FormData();
        formData.append("files", file); // 文件对象
        let url = this.fileUrl + '/' + this.showdata.id + '/files/picture/adtProblems'
        this.$http.post(url, formData).then((res) => {
          if (res.data.result == "success") {
            this.$Message.info("文件上传成功")
            this.getFilesItem(this.showdata.id);
          }
        })
      }

      return false
    },
    async getFiles(id) {
      this.upLoadList1.length = 0
      let url = this.fileUrl + '/' + id + '/files/picture'
      let data = {field: 'adtProblems'}
      await this.$http.get(url, {params: data}).then((res) => {
        if (res.data.result == "success") {
          if (res.data.data) {
            this.upLoadList1 = res.data.data
            this.upLoadList1 = this.upLoadList1.map(v => {
              v.url = this.fileUrl + '/file/' + v.id;
              return v
            })
          }
        }
      })
    },
    async getFilesItem(id) {
      this.uploadItems.length = 0
      let url = this.fileUrl + '/' + id + '/files/picture'
      let data = {field: 'adtProblems'}
      await this.$http.get(url, {params: data}).then((res) => {
        if (res.data.result == "success") {
          if (res.data.data) {
            this.uploadItems = res.data.data
            this.uploadItems = this.uploadItems.map(v => {
              v.url = this.fileUrl + '/file/' + v.id;
              return v
            })
          }
        }
      })
    },
    handleRemove(file) {
      //删除操作
      let _this = this;
      let config = {
        title: '系统提示',
        content: '确认删除图片吗?',
        okText: '确定',
        cancelText: '取消',
        onOk: function () {

          _this.$Spin.show({
            render: (h) => {
              return h('div', [
                h('Icon', {
                  'class': 'demo-spin-icon-load',
                  props: {
                    type: 'ios-loading',
                    size: 18
                  }
                }),
                h('div', 'Loading')
              ])
            }
          });
          _this.uploadImgs.splice(_this.uploadImgs.indexOf(file), 1);

          _this.$http.delete(Api.downloadPTWSchemeFile + '/' + file.id).then((res) => {
            _this.$Message.success('删除成功');
            _this.$Spin.hide();
          }).catch(e => {
            _this.$Spin.hide();
            _this.$Message.error('删除失败' + e);
          })
        },
        onCancel: function () {
        }
      }
      this.$Modal.confirm(config);
    },
    openMissionSelectModal() {
      this.missionSelectModal = true
    },
    openSelect() {

      let userName = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserName"]
      this.form1datacopy = {
        auditTime: new Date(),
        planTaskName: this.$route.query.missionName,
        planTaskId: this.$route.query.missionId,
        auditedOrgName: this.$route.query.auditedOrgName,
        auditedOrgId: this.$route.query.auditedOrgId,
        problemState: '0',
        problemStateName: '待确认',
        auditorName: JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserName"],
        auditorId: JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserId"],
        sceneId: this.$route.query.sceneId,
        teamId: this.$route.query.teamId,
        basicsId: this.$route.query.basicsId,

        problemId: this.get_uuid(),
        auditScore: 1,
        createDate: this.formatDate(new Date(), 'yyyy-MM-dd'),
        createUserName: userName
      }
      this.model11 = true
      this.upLoadList1 = []
      this.add = true;
    },

    handleView(name, url) {
      this.viewUrl = url;
      this.imgName = name;
      this.visible = true;
    },

    handleCancel() {

      this.model12 = false;

    },
    rectLeaderChange(appStatus) {
      if (appStatus) {
        this.form1datacopy.rectLeaderId = appStatus.value;
        this.form1datacopy.rectLeader = appStatus.label;
      }
    },
    queryAdminMessage() {
      if (this.form1.planTaskId) {
        this.$http.post(Api.selectMissionById + this.form1.planTaskId).then((res) => {
          if (res.data.status === 200) {
            this.form1datacopy = res.data.data.adtMission;
            this.auditHandlers = res.data.data.auditHandlers;
            this.model2 = true;
          } else if (res.data.status == 202) {
            this.$Message.warning(res.data.msg)
          } else {
            this.$Message.error(res.data.msg)
          }

        }).catch(e => {
          this.$Message.error("指派失败")
        })
      } else {
        this.$Message.warning("请先选择审计任务！")
      }
    },
    addInfo() {
      this.dataForm = {};
      this.setCurrentExpectUserName = {};
      this.setCurrentAssignUserName = {
        label: JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserName"],
        value: JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserId"]
      };
      setTimeout(() => {
        //this.$refs.childUser1.setCurrentUser();
      }, 300);
      this.model1 = true;
    },

    setExpectUserName(data) {
      this.dataForm.expectUserName = data;
    },
    setExpectUserId(data) {
      this.dataForm.expectUser = data[data.length - 1];
    },

    setAssignUserName(data) {
      this.dataForm.assignUserName = data;
    },
    setAssignUserId(data) {
      this.dataForm.assignUserId = data[data.length - 1];
    },

    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    submit(name) {
      let _this = this;
      let ids = ''
      if (this.uploadItems) {
        this.uploadItems.forEach(v => {
          ids += ":" + v.id
        })
      }
      this.showdata.fileId = ids
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
          this.showdata.updateUserId = userId;
          this.showdata.updateOrgId = orgId;
          this.$http.post(Api.saveRectificationList, this.showdata).then((res) => {
            if (res.data.status == '200') {
              this.$Message.success('成功');
              this.model12 = false;
              this.query()

            } else if (res.data.status == '201') {
              this.$Message.error(res.data.msg);
              this.model12 = false;
            }
            _this.submitLoading = false;

          }).catch(e => {
            _this.submitLoading = false;
            this.model12 = false;
            this.query();
            this.$Message.error("数据获取失败")
          })


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    query() {
      this.buttonLoading = true
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        id: this.$route.query.missionId,
        createUserId: this.user.userId,
        orgId: this.user.companyId,
        auditedOrgId: this.$route.query.auditedOrgId,
        executorId: this.executorId
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.queryRectificationList;
      this.$http.get(url, {params: data}).then((res) => {

        this.dataTable = res.data.data.data;
        this.dataTable.forEach(item => {
          if (item.verification != null && item.verification !== '0') {
            item['_disabled'] = true;
          }
        })
        this.pagedata.total = res.data.data.totalSize;
        this.buttonLoading = false

      }).catch(e => {
        console.log(e)
        this.$Message.error("数据获取失败")
      })
    },
    reset() {
      this.form1 = {};
      this.query();
    },

    deleteData(params) {
      let url = Api.deleteAdtProblem;

      this.$Modal.confirm({
        title: '数据删除',
        content: '<p>确定删除该条信息</p>',
        okText: '确认',
        onOk: () => {
          this.$http.get(url, {params: {id: params.row.problemId}}).then((res) => {
            if (res.status === 200) {
              this.$Message.success('成功');
              this.query()
            } else if (res.data.status === 201) {
              this.$Message.error(res.data.msg);

            }
          }).catch(e => {
            this.$Message.error('请求失败' + e);
          })
        },
        cancelText: '取消'
      });
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    downloadFile() {
      let data = {
        id: this.$route.query.missionId,
        basicsId: this.$route.query.basicsId,
        sceneId: this.$route.query.sceneId,
        teamId: this.$route.query.teamId,
      };
      this.$http.get(Api.downloadAdtProblemRectMgr, {
        params: data,
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "审计问题清单(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      return a;
    },
    remove1(mainId, id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        var index = this.uploadItems.indexOf(id);
        if (index > -1) {
          this.uploadItems.splice(index, 1);
        }
        this.getFilesItem(mainId)
      })
    },
    async showData(data, flag) {
      let _this = this
      data.row.createDate = this.formatDate(new Date(data.row.createDate), 'yyyy-MM-dd')
      this.getFiles(data.row.problemId)
      this.getFilesItem(data.row.id)
      if (flag == 1) {
        this.showdata = JSON.parse(JSON.stringify(data.row));

        this.model3 = true;
      } else {
        _this.completeTime = data.row.completeTime
        _this.showdata = JSON.parse(JSON.stringify(data.row));
        if (_this.showdata.id == null) {
          _this.showdata.id = _this.get_uuid();
          _this.showdata.personName = _this.user.userName;
          _this.showdata.phone = _this.user.mobileNumber;
          _this.showdata.verification = '0'
          _this.showdata.missionId = _this.showdata.problemId

        }
        _this.showdata.personName = _this.user.userName;
        _this.showdata.phone = _this.user.mobileNumber;
        this.model12 = true;
      }
    },
  },

  watch: {},

}
</script>
<style lang='css' scoped>
@import '../../../index.css';
</style>
